//
//  InstallationTypeView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/3.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
class InstallationTypeViewModel: NSObject {
    var pvd_id: String = ""
    var heater_installation_type: HeaterInstallationTypeValue = .None {
        didSet{
            self.installation_type_value = self.heater_installation_type.rawValue
        }
    }
    var installation_type: InstallationTypeValue = .none {
        didSet{
            self.installation_type_value = self.installation_type.rawValue
        }
    }
    @objc dynamic var installation_type_value: String = ""
    @objc dynamic var additional_upgrade_system_details: String = ""
}
class InstallationTypeView: View {
    @objc dynamic var viewModel = InstallationTypeViewModel()
    lazy var disposeBag = DisposeBag()
    //
    var additionalTipBtnClosure: (()->Void)?
    //四个installation type 按钮
    let newLabel = OptionTypeLabel(InstallationTypeName.New.rawValue)
    let replaceLabel =  OptionTypeLabel(InstallationTypeName.Replacement.rawValue)
    let extensionLabel =  OptionTypeLabel(InstallationTypeName.Extension.rawValue)
    let additionalLabel =  OptionTypeLabel(InstallationTypeName.Additional.rawValue)
    let installationTypeDescripLabel = ContentLabel(R.font.interRegular(size: 13), hexStr: "#292D3266")
    lazy var installationTypeRequiredLabel: BaseLabel = {
        return ViewFactory.shared.generateRequiredLabel()
    }()
    //additional infomation
    var additionalInfoTitleView: LabelWithRedStarView!
    lazy var additionalInfoTextView: TextViewWithRequiredView = {
        let view = TextViewWithRequiredView(.addtionalInfo)
        view.textView.placeholder = R.string.localizable.additionalUpgradeSystemInformationMustBeBetween7And4000DigitsEgExisting3kwSystemLocatedOnNorthRoof6NewPanelsReplacedUpgradedToOldSystemLocatedOnSouthWestFacingSouth()
        view.textView.limitLength = 4000
        view.textView.limitLabelFont = R.font.interRegular(size: 14)
        view.textView.limitLabelColor = UIColor(hexStr: "#292D3299")
        return view
    }()
    
    override func setUpView() {
        //1.installationType title
        let installationTypeTitle = LabelWithRedStarView(R.string.localizable.installationType())
        self.addSubview(installationTypeTitle)
        installationTypeTitle.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview()
            make.height.width.greaterThanOrEqualTo(0)
        }
        //1.1.installationType textfield
        //new
        self.addSubview(newLabel)
        newLabel.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeTitle.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //replaceLabel
        self.addSubview(replaceLabel)
        replaceLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(newLabel)
            make.left.equalTo(newLabel.snp.right).offset(Constant.InternalMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //extensionLabel
        self.addSubview(extensionLabel)
        extensionLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(newLabel)
            make.left.equalTo(replaceLabel.snp.right).offset(Constant.InternalMargin)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //
        let newSize = newLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: 40 * Constant.currentSizeScale ))
        let replaceSize = replaceLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: 40 * Constant.currentSizeScale ))
        let extensionSize = extensionLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: 40 * Constant.currentSizeScale ))
        let additionalSize = additionalLabel.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: 40 * Constant.currentSizeScale ))
        let maxWidth = newSize.width + replaceSize.width + extensionSize.width + additionalSize.width + Constant.InternalMargin * 3 + Constant.AllOutMargin * 2//16是所有边距，12是中间边距
        if APPConfig.WidthForPortrait < maxWidth{//如果四个按钮的长度加上间隔，加上两边的margin大于屏幕宽度就换行
            //additionalLabel
            self.addSubview(additionalLabel)
            additionalLabel.snp.makeConstraints { (make) in
                make.top.equalTo(newLabel.snp.bottom).offset(Constant.InternalMargin)
                make.left.equalTo(newLabel)
                make.height.width.greaterThanOrEqualTo(0)
            }
        }else{
            //additionalLabel
            self.addSubview(additionalLabel)
            additionalLabel.snp.makeConstraints { (make) in
                make.centerY.equalTo(newLabel)
                make.left.equalTo(extensionLabel.snp.right).offset(Constant.InternalMargin)
                make.right.lessThanOrEqualToSuperview().offset(-Constant.AllOutMargin)
                make.height.width.greaterThanOrEqualTo(0)
            }
        }
        //installationTypeDescripLabel
        installationTypeDescripLabel.textAlignment = .left
        installationTypeDescripLabel.numberOfLines = 0
        self.addSubview(installationTypeDescripLabel)
        installationTypeDescripLabel.snp.makeConstraints { (make) in
            if APPConfig.WidthForPortrait < maxWidth {
                make.top.equalTo(additionalLabel.snp.bottom).offset(Constant.TitleTextMargin)
            }else{
                make.top.equalTo(newLabel.snp.bottom).offset(Constant.TitleTextMargin)
            }
            make.left.equalTo(newLabel)
            make.right.equalTo(-Constant.AllOutMargin)
            make.height.greaterThanOrEqualTo(0)
        }
        //必填项tip
        self.addSubview(installationTypeRequiredLabel)
        installationTypeRequiredLabel.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeDescripLabel.snp.bottom).offset(2)
            make.left.right.equalTo(installationTypeDescripLabel)
            make.height.greaterThanOrEqualTo(0)
        }
        //3.Additional Information
        additionalInfoTitleView = LabelWithRedStarView(R.string.localizable.additionalUpgradeSystemInformation())
        additionalInfoTitleView.titleLabel.numberOfLines = 0
        self.addSubview(additionalInfoTitleView)
        additionalInfoTitleView.snp.makeConstraints { (make) in
            make.top.equalTo(installationTypeRequiredLabel.snp.bottom).offset(Constant.TopBottomMargin)
            make.left.equalTo(installationTypeTitle)
            make.height.width.greaterThanOrEqualTo(0)
        }
        //additionalTipBtn
        let additionalTipBtn = UIButton()
        additionalTipBtn.setImage(UIImage(named: "installation_detail_spv_tip_icon"), for: UIControl.State.normal)
        self.addSubview(additionalTipBtn)
        additionalTipBtn.snp.makeConstraints { (make) in
            make.left.equalTo(additionalInfoTitleView.snp.right)
            make.right.lessThanOrEqualToSuperview()
            make.centerY.equalTo(additionalInfoTitleView)
            make.height.width.equalTo(30)
        }
        //3.1.Additional Information textview
        self.addSubview(additionalInfoTextView)
        additionalInfoTextView.snp.makeConstraints { (make) in
            make.top.equalTo(additionalInfoTitleView.snp.bottom).offset(Constant.TitleTextMargin)
            make.left.equalTo(installationTypeTitle)
            make.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //new
        newLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.New)
        }).disposed(by: self.disposeBag)
        //replacement
        replaceLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.Replacement)
        }).disposed(by: self.disposeBag)
        //extensionLabel
        extensionLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.Extension)
        }).disposed(by: self.disposeBag)
        //additionalLabel
        additionalLabel.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            self?.selectInstallationType(.Additional)
        }).disposed(by: self.disposeBag)
        
        //
        additionalInfoTextView.endEditingClosure = {[weak self] (text) in
            self?.viewModel.additional_upgrade_system_details = text
            if text != "" {
                if Tool().isValidAddtionalInfo(text) == false{//如果超过4000
                    self?.additionalInfoTextView.showInvalidMsg(R.string.localizable.additionalUpgradeSystemInformationMustBeBetween7And4000Digits())
                }else{
                    self?.additionalInfoTextView.hideInvalidMsg()
                }
            }
        }
        
        additionalTipBtn.addTarget(self, action: #selector(additionalTipBtnClick), for: UIControl.Event.touchUpInside)
        additionalInfoTitleView.showRedStar(false)
    }
    func setData(_ model: InstallationTypeViewModel, editFlag: Bool = false){
        self.viewModel = model
        self.selectInstallationType(self.viewModel.installation_type)
        if self.viewModel.additional_upgrade_system_details.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: .newlines) != ""{
            self.additionalInfoTextView.textView.text = self.viewModel.additional_upgrade_system_details
            self.additionalInfoTextView.textView.textChange(Notification(name: UITextView.textDidChangeNotification))//通知隐藏placeholder
        }
        //检查Additional/Upgrade System Information是否是必填项，显示red star
        self.checkIfRequirdAddtional(self.viewModel.installation_type)
        //
        if editFlag {
            self.validateAllRequiredFieldWhenEdit()
        }
    }
    //
    private func selectInstallationType(_ type: InstallationTypeValue){
        self.newLabel.setUnSelect()
        self.replaceLabel.setUnSelect()
        self.extensionLabel.setUnSelect()
        self.additionalLabel.setUnSelect()
        //
        var tipMsg = ""
        switch type {
        case .New:
            self.newLabel.setSelect()
            tipMsg = "The first system installed at the address"
        case .Replacement:
            self.replaceLabel.setSelect()
            tipMsg = "Previous system removed/decommissioned."
        case .Additional:
            self.additionalLabel.setSelect()
            tipMsg = "New separate system at the same address."
        case .Extension:
            tipMsg = "Components added to existing system."
            self.extensionLabel.setSelect()
        default:
            break
            
        }
        self.installationTypeDescripLabel.text = tipMsg
        //隐藏必填项tip msg
        self.installationTypeRequiredLabel.text = ""
        self.viewModel.installation_type = type//创建Job的地方用
        self.checkIfRequirdAddtional(type)
        
    }
    //MARK: - 只用于已创建Job的信息编辑， 进入编辑界面如果save 按钮不可用，要给与相应提示
    private func validateAllRequiredFieldWhenEdit(){
        if self.viewModel.installation_type == .none {
            self.installationTypeRequiredLabel.text = R.string.localizable.thisIsRequired()
        }else{
            self.installationTypeRequiredLabel.text = ""
        }
        self.additionalInfoTextView.checkTextViewIfValid()
    }
    @objc func additionalTipBtnClick(){
        self.endEditing(true)
        self.additionalTipBtnClosure?()
    }
    private func checkIfRequirdAddtional(_ installationType: InstallationTypeValue?){
        if let type = installationType {
            if type == .New || type == .Replacement{
                additionalInfoTitleView.showRedStar(false)
                additionalInfoTextView.needCheckFlag = false
                additionalInfoTextView.checkTextViewIfValid()
                let text = self.additionalInfoTextView.textView.text ?? ""
                if text != "" && Tool().isValidAddtionalInfo(text) == false{
                    additionalInfoTextView.showInvalidMsg(R.string.localizable.additionalUpgradeSystemInformationMustBeBetween7And4000Digits())
                }else{
                    additionalInfoTextView.hideInvalidMsg()
                }
            }else if type == .Extension || type == .Additional{
                additionalInfoTitleView.showRedStar(true)
                additionalInfoTextView.needCheckFlag = true
            }
        }else{
            additionalInfoTitleView.showRedStar(false)
        }
    }
}
